//
//  CountView.m
//  BaseFrame
//
//  Created by 孟学浩 on 2017/4/5.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "CountView.h"

@interface CountView()

@property (nonatomic,strong) UILabel *countLabel;

@end

@implementation CountView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.count = 1;
        self.layer.borderWidth = .5;
        self.layer.borderColor = [UIColor grayColor].CGColor;
        
        UIButton *subBtn = [UIButton new];
        [subBtn setTitle:@"-" forState:UIControlStateNormal];
        subBtn.backgroundColor = [UIColor grayColor];
        [subBtn addTarget:self action:@selector(subEvent) forControlEvents:UIControlEventTouchUpInside];

        
        UIButton *addBtn = [UIButton new];
        [addBtn setTitle:@"+" forState:UIControlStateNormal];
        addBtn.backgroundColor = [UIColor grayColor];
        [addBtn addTarget:self action:@selector(addEvent) forControlEvents:UIControlEventTouchUpInside];
        
        _countLabel = [UILabel new];
        _countLabel.font = DEF_FontSize_12;
        _countLabel.text = @"1";
        _countLabel.textAlignment = NSTextAlignmentCenter;
        _count = 1;
        
        [self addSubview:subBtn];
        [self addSubview:addBtn];
        [self addSubview:_countLabel];
        
        CGFloat width = frame.size.width/3.;
        subBtn.frame = CGRectMake(0, 0, width, frame.size.height);
        addBtn.frame = CGRectMake(self.frame.size.width - width, 0, width, frame.size.height);
        _countLabel.frame = CGRectMake(CGRectGetMaxX(subBtn.frame), 0, width, frame.size.height);
    }
    return self;
}

- (void)setCount:(int)count{
    _count = count;
    _countLabel.text = [NSString stringWithFormat:@"%d",_count];
}

- (void)subEvent{
    if (_count != 1) {
        _count -- ;
        _countLabel.text = [NSString stringWithFormat:@"%d",_count];
        if (self.valueChangeHandle) {
            self.valueChangeHandle(_count);
        }
    }
}

- (void)addEvent{
    _count ++;
    _countLabel.text = [NSString stringWithFormat:@"%d",_count];
    if (self.valueChangeHandle) {
        self.valueChangeHandle(_count);
    }
}

@end
